package com.cqc.web;

import com.cqc.common.Result;
import com.cqc.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author cui
 * @date 2025/3
 * 演示 DeferredResult
 **/
@Controller
@RequestMapping("/deferredResult/")
public class DefferredResultController {


    /**
     * http://localhost:8080/deferredResult/f1
     */
    @GetMapping("f1")
    @ResponseBody
    public Result f1() {
        return Result.successMsg(Thread.currentThread().getName());
    }

    /**
     * http://localhost:8080/deferredResult/f2
     */
    @GetMapping("f2")
    @ResponseBody
    public Result f2() {
        try {
            TimeUnit.MINUTES.sleep(1L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("f2");
        return Result.successMsg(Thread.currentThread().getName());
    }


    /**
     * 超时
     * http://localhost:8080/deferredResult/addOrder1?orderId=1
     */
    @GetMapping("addOrder1")
    @ResponseBody
    public DeferredResult<String> addOrder1(String orderId) {
        DeferredResult<String> deferredResult = new DeferredResult<>(3000L);
        deferredResult.onTimeout(() -> {
            deferredResult.setResult("超时了");
        });
        deferredResult.onError(e -> {
            deferredResult.setErrorResult("错误");
        });
        deferredResult.onCompletion(() -> {
            System.out.println("onCompletion");
        });
        return deferredResult;
    }


}
